/**
 * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package cn.bluemobi.dylan.step.activity.skeleton;

import static cn.bluemobi.dylan.step.activity.skeleton.HumanSkeletonActivity.isYogaChecked;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hms.mlsdk.common.MLFrame;
import com.huawei.hms.mlsdk.skeleton.MLSkeleton;
import com.huawei.hms.mlsdk.skeleton.MLSkeletonAnalyzerSetting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bluemobi.dylan.step.activity.adapter.skeleton.GridItem;
import cn.bluemobi.dylan.step.transactor.LocalSketlonTranstor;
import cn.bluemobi.dylan.step.util.BitmapUtils;
import cn.bluemobi.dylan.step.views.graphic.CameraImageGraphic;
import cn.bluemobi.dylan.step.views.graphic.LocalSkeletonGraphic;
import cn.bluemobi.dylan.step.views.overlay.GraphicOverlay;


public class  TemplateActivity extends AppCompatActivity {
    private static final String TAG = "TemplateActivity";

    private static final String KEY = "key";

    private static final int REQUEST_IMAGE_CAPTURE = 1001;

    private static final int REQUEST_CHOOSE_IMAGE = 1002;

    private static final int UNKNOW = -1;

    private static Map<String, GridItem> templateDataMap = new HashMap<String, GridItem>();

    private static int sSelectedIndex = UNKNOW;


    private Uri imageUri;

    private Bitmap originBitmap;

    private List<GridItem> templateDatalist = new ArrayList<GridItem>();

    private LocalSketlonTranstor imageProcessor;
    private GraphicOverlay graphicOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MLSkeletonAnalyzerSetting settings;
        if (isYogaChecked()) {
            settings = new MLSkeletonAnalyzerSetting.Factory()
                    .setAnalyzerType(MLSkeletonAnalyzerSetting.TYPE_YOGA)
                    .create();
        } else {
            settings = new MLSkeletonAnalyzerSetting.Factory().create();
        }
        imageProcessor = new LocalSketlonTranstor(settings, this, null);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            loadImage();
        } else if (requestCode == REQUEST_CHOOSE_IMAGE && resultCode == RESULT_OK) {
            imageUri = data.getData();
            loadImage();
        }
    }

    private void loadImage() {
        originBitmap = BitmapUtils.loadFromPath(TemplateActivity.this, imageUri, getWidth(), getHeight());
        if(originBitmap == null) {
            return;
        }
        MLFrame frame = new MLFrame.Creator().setBitmap(originBitmap).create();
        imageProcessor.detectInImage(frame).addOnSuccessListener(new OnSuccessListener<List<MLSkeleton>>() {
            @Override
            public void onSuccess(List<MLSkeleton> results) {
                if (results == null) {
                    Log.d(TAG, "results == null");
                    return;
                }
                if (results.size() > 0) {
                    graphicOverlay.clear();
                    CameraImageGraphic imageGraphic = new CameraImageGraphic(graphicOverlay, originBitmap);
                    graphicOverlay.addGraphic(imageGraphic);

                    LocalSkeletonGraphic skeletonGraphic = new LocalSkeletonGraphic(graphicOverlay, results);
                    graphicOverlay.addGraphic(skeletonGraphic);
                    graphicOverlay.postInvalidate();

                    GridItem gridItem = new GridItem();
                    gridItem.setBitmap(BitmapUtils.loadBitmapFromView(graphicOverlay, originBitmap.getWidth(),
                            originBitmap.getHeight()));
                    gridItem.setSkeletonList(results);
                } else {
                    Toast.makeText(TemplateActivity.this, "No skeleton data, create template fail.", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.d(TAG, "onFailure");
            }
        });
    }

    private int getWidth() {
        Display display = getWindowManager().getDefaultDisplay();
        int width;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            width = display.getHeight();
        } else {
            width = display.getWidth();
        }
        return width;
    }

    private int getHeight() {
        Display display = getWindowManager().getDefaultDisplay();
        int height;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            height = display.getWidth();
        } else {
            height = display.getHeight();
        }
        return height;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imageProcessor.stop();
    }


    public static Map<String, GridItem> getTemplateDataMap() {
        return templateDataMap;
    }

    public static int getSelectedIndex() {
        return sSelectedIndex;
    }


    public static String getKey() {
        return KEY;
    }
}
